<?php

namespace App\Http\Controllers;

use App\Models\User;
use Illuminate\Http\Request;
use Validator;
use App\Http\Requests;
use App\Http\Controllers\Controller;

class TestController extends Controller
{

    /**
     * 添加用户
     * @param Request $request
     * @return array|\Illuminate\Http\JsonResponse
     */
    public function addUser(Request $request)
    {
        //验证数据
        $validator=Validator::make($request->all(),[
            "name"=>"required|max:20",
            "password"=>"required|max:60",
            "email"=>"required|email|max:255",
        ]);

        if($validator->fails()){
            return response()->json(array('error'=>$validator->errors()));
        }

        $data=$request->all();

        if(User::where('email',$data['email'])->first()!=null)
        {
            return ['error'=>"该用户已经存在"];
        }
        $user=new User();
        $user->name=$data['name'];
        $user->password=$data['password'];
        $user->email=$data['email'];
        $user->save();

        return ['success'=>"增加用户成功"];
    }


    public function getUserEmail(Request $request)
    {
        //验证数据
        $validator=Validator::make($request->all(),[
            "name"=>"required|max:20",
        ]);

        if($validator->fails()){
            return response()->json(array('error'=>$validator->errors()));
        }
        $data=$request->all();
        $res=User::where('name',$data['name'])->first();
        if($res==null)
        {
            return self::result(false,"不存在该用户",null);
        }
        else
        {
            return self::result(true,"获取用户邮箱成功",$res->email);
        }
    }

    public static function result($success,$info,$res)
    {
        return ['success'=>$success,'info'=>$info,'result'=>$res];
    }
}
